package com.flowerplus.store.common.data.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import com.flowerplus.store.common.data.utils.ui.ResourcesUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Tegend on 2016/4/13.
 */
public class FileUtil {

    private static FileUtil sFileUtil = new FileUtil();


    public final String CACHE = "data_cache".hashCode() + "";
    public final String APK = "apk".hashCode() + "";
    public final String ICON = "icon_cache".hashCode() + "";
    public final String ABOUT = "about_cache".hashCode() + "";
    public final String HEADER = "header_cache".hashCode() + "";
    public final String DB = "db_cache".hashCode() + "";
    public final String LOG = "log".hashCode() + "";
    public final String LOG_PRINT = "log_print".hashCode() + "";
    public static String ROOT = "jmx".hashCode() + "";
    public final String EXCEPTION = "exception".hashCode() + "";
    public final String ZIP = "zip".hashCode() + "";
    private Context mContext;

    public static FileUtil getInstance() {
        if (sFileUtil == null) {
            sFileUtil = new FileUtil();
        }
        return sFileUtil;
    }

    public FileUtil(Context context, ResourcesUtil resourcesUtil) {
        this.mContext = context;
    }

    public FileUtil() {
    }

    /**
     * 获取图片的缓存的路径
     *
     * @return
     */
    public File getIconDir() {
        return getDir(ICON);
    }

    public File getAboutDir() {
        return getDir(ABOUT);
    }

    /**
     * 获取修改头像是裁剪后图片的缓存的路径
     *
     * @return
     */
    public File getHeaderDir() {
        return getDir(HEADER);
    }

    public File getApkDir() {
        return getDir(APK);
    }

    /**
     * 获取数据库缓存路径
     *
     * @return
     */
    public File getDbDir() {
        return getDir(DB);

    }

    //log路径
    public File getLogDir() {
        return getDir(LOG);

    }

    //zip路径
    public File getZipDir() {
        return getDir(ZIP);

    }

    public File getPrintLogDir() {
        return getDir(LOG_PRINT);
    }

    public File getException() {
        return getDir(EXCEPTION);
    }

    /**
     * 获取缓存路径
     *
     * @return
     */
    public File getCacheDir() {
        return getDir(CACHE);
    }

    public File getDir(String cache) {
        StringBuilder path = new StringBuilder();
        if (isSDAvailable()) {  //SD卡是否可用
            path.append(Environment.getExternalStorageDirectory()
                    .getAbsolutePath());
            path.append(File.separator);// '/'
            path.append(ROOT);// /mnt/sdcard/ggh
            path.append(File.separator);
            path.append(cache);// /mnt/sdcard/ggh/cache

        } else {  //不可用
            File filesDir = mContext.getCacheDir();    //  cache  getFileDir file
            path.append(filesDir.getAbsolutePath());// /data/data/com.android.ggh/cache
            path.append(File.separator);///data/data/com.android.ggh/cache/
            path.append(cache);///data/data/com.android.ggh/cache/cache
        }
        File file = new File(path.toString());
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();// 创建文件夹
        }
        return file;
    }

    public void getImageDir() {

    }

    /**
     * 获取根目录path
     *
     * @return
     */
    public File getRootDir() {
        StringBuilder path = new StringBuilder();
        if (isSDAvailable()) {  //SD卡是否可用
            path.append(Environment.getExternalStorageDirectory()
                    .getAbsolutePath());
            path.append(File.separator);// '/'
            path.append(ROOT);// /mnt/sdcard/ggh
            path.append(File.separator);
//            path.error(cache);// /mnt/sdcard/ggh/cache

        } else {  //不可用
            File filesDir = mContext.getCacheDir();    //  cache  getFileDir file
            path.append(filesDir.getAbsolutePath());// /data/data/com.android.ggh/cache
            path.append(File.separator);///data/data/com.android.ggh/cache/
//            path.error(cache);///data/data/com.android.ggh/cache/cache
        }
        File file = new File(path.toString());
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();// 创建文件夹
        }
        return file;

    }

    private boolean isSDAvailable() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存图片
     *
     * @param filePath
     * @param bitmap
     * @param size
     * @return
     */
    public File saveImage(String filePath, Bitmap bitmap, long size) {
        Utils.checkNotNull(bitmap, "bitmap cannot be null");
        File result = new File(filePath.substring(0, filePath.lastIndexOf("/")));

        if (!result.exists() && !result.mkdirs()) return null;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        int options = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);

        while (stream.toByteArray().length / 1024 > size && options > 6) {
            stream.reset();
            options -= 6;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);
        }

        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new File(filePath);
    }


    public File saveFile(String filePath, InputStream inputStream) {
        byte[] buf = new byte[2048];
        int len;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            while ((len = inputStream.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new File(filePath);
    }


    public boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        return deleteFile(file);
    }


    public boolean deleteDirectory(String filePath) {
        boolean flag = false;
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        for (int i = 0; files != null && i < files.length; i++) {
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        return dirFile.delete();
    }

    public boolean deleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                return deleteFile(filePath);
            } else {
                return deleteDirectory(filePath);
            }
        }
    }


}
